package com.tools.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 生成文件
 * 
 * 
 */
public class Base {

	/**
	 * 创建文件（包括该文件的父级文件夹）
	 * 
	 * @param path
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	private static String createFile(String path, String fileName) {
		File dirFile = new File(path);
		if (!dirFile.exists() && !dirFile.isDirectory()) {
			dirFile.mkdirs();
		}
		if (!path.substring(path.length() - 1, path.length()).equals("/")) {
			path = (new StringBuilder(String.valueOf(path))).append("/")
					.toString();
		}
		File file = new File((new StringBuilder(String.valueOf(path))).append(
				fileName).toString());
		if (file != null && !file.isFile()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return (new StringBuilder(String.valueOf(path))).append(fileName)
				.toString();
	}

	/**
	 * 创建文件内容
	 * 
	 * @param templateType
	 * @param folderPath
	 * @throws IOException
	 */
	private static void createFileContent(String templateFile,
			String sourceFile, CodeSet codeSet) {
		createFileContent(templateFile, sourceFile, codeSet, null);
	}

	/**
	 * 创建文件内容
	 * 
	 * @param templateType
	 * @param folderPath
	 * @throws IOException
	 */
	private static void createFileContent(String templateFile,
			String sourceFile, CodeSet codeSet, Class clazz) {
		try {
			String className = codeSet.getClassName();
			StringBuffer packageName = new StringBuffer(codeSet
					.getPackageName().replace("\\", "."));
			BufferedReader buffRader = new BufferedReader(new FileReader(
					templateFile));
			StringBuffer basePackageName = new StringBuffer(codeSet
					.getBasePackageName().replace("\\", "."));
			BufferedWriter buffWriter = new BufferedWriter(new FileWriter(
					sourceFile));
			String line = buffRader.readLine();
			while (line != null) {
				line = line.replaceAll("&className&", className);
				// 这是其中一个bug
				if (className.length() > 1) {
					line = line.replaceAll(
							"&className.toFirstLowerCase&",
							className.substring(0, 1).toLowerCase()
									+ className.substring(1));
				}
				line = line.replaceAll("&className.toLowerCase&",
						className.toLowerCase());
				line = line.replaceAll("&basePackageName&",
						basePackageName.toString());
				line = line.replaceAll("&packageName&", packageName.toString()
						.substring(packageName.lastIndexOf(".") + 1));
				line = line.replaceAll("&classPackage&",
						codeSet.getClassPackage());
				if (clazz != null) {
					if (line.indexOf("&queryjs&") >= 0) {
						ParseEntitySet pe = new ParseEntitySet();
						line = line.replace("&queryjs&",
								pe.parseField("queryjs", clazz));
					}
					if (line.indexOf("&query&") >= 0) {
						ParseEntitySet pe = new ParseEntitySet();
						line = line.replace("&query&",
								pe.parseField("query", clazz));
					}
					if (line.indexOf("&initList&") >= 0) {
						ParseEntitySet pe = new ParseEntitySet();
						line = line.replace("&initList&",
								pe.parseField("list", clazz));
					}
					if (line.indexOf("&initEdit&") >= 0) {
						ParseEntitySet pe = new ParseEntitySet();
						String html = pe.parseField("edit", clazz);
						// System.out.println(pe.parseField("edit", clazz));
						// line = line.replaceAll("&initEdit&",
						// pe.parseField("edit", clazz));
						int start = line.indexOf("&initEdit&");
						int end = start + "&initEdit&".length();
						line = line.substring(0, start) + "\n" + html + "\n"
								+ line.substring(end);
					}
					if (line.indexOf("&initDetail&") >= 0) {
						ParseEntitySet pe = new ParseEntitySet();
						String html = pe.parseField("detail", clazz);
						int start = line.indexOf("&initDetail&");
						int end = start + "&initDetail&".length();
						line = line.substring(0, start) + "\n" + html + "\n"
								+ line.substring(end);
					}
				}
				buffWriter.write(line);
				buffWriter.newLine();
				line = buffRader.readLine();
			}
			buffWriter.flush();
			buffWriter.close();
			buffRader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据模版文件生成代码
	 * 
	 * @param entity
	 *            实体 根据此实体生成代码
	 * @param codeEntity
	 *            代码实体设置信息
	 * @param templateType
	 *            模版类型 如：Dao
	 * @param basePath
	 *            生产代码存放路径 如： D：\workspace\demo
	 */
	@SuppressWarnings("rawtypes")
	public static void generateSource(Class codeclass, CodeSet codeEntity,
			String templateType) {
		codeEntity.setClassName(codeclass.getName());
		CodeSet code = paramSet(codeEntity);
		code.setTemplateType(templateType.toLowerCase());
		if (templateType.equals("Dao")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath()).append(code.getSourceName())
					.append("\\").append(code.getPackageName()).append("\\")
					.append(templateType.toLowerCase());
			String file = createFile(filePath.toString(), (new StringBuilder(
					code.getClassName())).append(templateType).append(".java")
					.toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateDao.template");
			createFileContent(templatePath.toString(), file, code);
		}
		if (templateType.equals("Service")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath()).append(code.getSourceName())
					.append("\\").append(code.getPackageName()).append("\\")
					.append(templateType.toLowerCase());
			String file = createFile(filePath.toString(), (new StringBuilder(
					code.getClassName())).append(templateType).append(".java")
					.toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateService.template");
			createFileContent(templatePath.toString(), file, code);
		}
		if (templateType.equals("ServiceImpl")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath()).append(code.getSourceName())
					.append("\\").append(code.getPackageName()).append("\\")
					.append("service").append("\\").append("impl");
			String file = createFile(filePath.toString(), (new StringBuilder(
					code.getClassName())).append(templateType).append(".java")
					.toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateServiceImpl.template");
			createFileContent(templatePath.toString(), file, code);
		}
		if (templateType.equals("Action")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath()).append(code.getSourceName())
					.append("\\").append(code.getPackageName()).append("\\")
					.append(templateType.toLowerCase());
			String file = createFile(filePath.toString(), (new StringBuilder(
					code.getClassName())).append(templateType).append(".java")
					.toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateAction.template");
			createFileContent(templatePath.toString(), file, code);
		}
		if (templateType.equals("Edit")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath())
					.append(code.getPageSource())
					.append("\\")
					.append(code.getPackageName().indexOf("\\") >= 0 ? code
							.getPackageName()
							.substring(
									code.getPackageName().lastIndexOf("\\") + 1)
							: code.getPackageName())
					.append("\\")
					.append(code.getClassName().length() < 2 ? code
							.getClassName().toLowerCase()
							: (code.getClassName().substring(0, 1)
									.toLowerCase() + code.getClassName()
									.substring(1)));
			String file = createFile(filePath.toString(), (new StringBuilder(
					templateType.toLowerCase())).append(code.getClassName())
					.append(".jsp").toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateEdit.template");
			createFileContent(templatePath.toString(), file, code, codeclass);
		}
		if (templateType.equals("List")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath())
					.append(code.getPageSource())
					.append("\\")
					.append(code.getPackageName().indexOf("\\") >= 0 ? code
							.getPackageName()
							.substring(
									code.getPackageName().lastIndexOf("\\") + 1)
							: code.getPackageName())
					.append("\\")
					.append(code.getClassName().length() < 2 ? code
							.getClassName().toLowerCase()
							: (code.getClassName().substring(0, 1)
									.toLowerCase() + code.getClassName()
									.substring(1)));
			String file = createFile(filePath.toString(), (new StringBuilder(
					templateType.toLowerCase())).append(code.getClassName())
					.append(".jsp").toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateList.template");
			createFileContent(templatePath.toString(), file, code, codeclass);
		}
		if (templateType.equals("Detail")) {
			StringBuffer filePath = new StringBuffer();
			filePath.append(code.getProjectPath())
					.append(code.getPageSource())
					.append("\\")
					.append(code.getPackageName().indexOf("\\") >= 0 ? code
							.getPackageName()
							.substring(
									code.getPackageName().lastIndexOf("\\") + 1)
							: code.getPackageName())
					.append("\\")
					.append(code.getClassName().length() < 2 ? code
							.getClassName().toLowerCase()
							: (code.getClassName().substring(0, 1)
									.toLowerCase() + code.getClassName()
									.substring(1)));
			String file = createFile(filePath.toString(), (new StringBuilder(
					templateType.toLowerCase())).append(code.getClassName())
					.append(".jsp").toString());
			StringBuffer templatePath = new StringBuffer();
			templatePath.append(code.getProjectPath())
					.append(code.getTemplateSource()).append("\\")
					.append("templateDetail.template");
			createFileContent(templatePath.toString(), file, code, codeclass);
		}
	}

	/**
	 * 设置生成代码属性
	 * 
	 * @param codeEntity
	 * @return
	 */
	public static CodeSet paramSet(CodeSet codeEntity) {
		String entity = codeEntity.getClassName();
		String className = entity.substring(entity.lastIndexOf(".") + 1,
				entity.length());
		String classPackage = entity.substring(0, entity.lastIndexOf("."));
		String packageName = classPackage.substring(0,
				classPackage.lastIndexOf("."));
		codeEntity.setProjectPath(new StringBuffer(codeEntity.getProjectPath())
				.append("\\").toString());
		codeEntity.setPackageName(packageName.replace(".", "\\"));
		codeEntity.setClassName(className);
		codeEntity.setClassPackage(entity);
		if (codeEntity.getSourceName() == null
				|| codeEntity.getSourceName().equals("")) {
			codeEntity.setSourceName("src");
		} else {
			codeEntity.setSourceName(codeEntity.getSourceName().replace(".",
					"\\"));
		}
		if (codeEntity.getPageSource() == null
				|| codeEntity.getPageSource().equals("")) {
			codeEntity.setPageSource("WebContent");
		} else {
			codeEntity.setPageSource(codeEntity.getPageSource().replace(".",
					"\\"));
		}
		codeEntity.setTemplateSource(codeEntity.getTemplateSource().replace(
				".", "\\"));
		return codeEntity;
	}
}
